#!/usr/bin/env python
# encoding: utf-8


"""
It provides a way to serve static files with spyro.
This class is not meant to be used for deploy purposes, but only for
development stages.
You can define more and more controllers serving static files, and then
map the routes to serve the static file, as any other controller.

By default it searches for the data in the "static" folder, but you can
define another path setting the configuration as shown below:

    contrib:
        static: 'static' # put here your path
"""

import os
import logging

from spyro import WebPage
from spyro.config.register import Register

log = logging.getLogger(__name__)

class StaticController(WebPage):
    """Use it inheriting your own controller.
    In your application define a controller that inherits from this as shown
    below:
    
    >>> from spyro.contrib.static import StaticController
    >>> class Static(StaticController):
    ...     pass
    
    And then put in your configuration the new route:
    
    '/static/(.*)': 'package.module.Static:index'  # refer to the index method
    
    
    Note: you have to inherit a controller inside your application, and is
    not reccomended to use directly spyro.contrib.static.StaticController just
    because defining the routes' "prefix" keyword would invalidate the reference
    (prepending the "prefix" value to spyro.contrib.static.StaticController).
    
    Note: it chooses the mime type by analyzing the file extension, it's
    meant for development only, to spread your static media files choose
    to serve them with a webserver.
    """
    
    def index(self, filename):
        if len(filename) > 0:
            try:
                folder = str(Register.contrib['static'])
            except:
                folder = 'static'
            
            try:
                filename = os.path.join(os.path.abspath(folder), filename)
                extension = filename.split('/')[-1].split('.')[-1]
                
                if (extension == 'jpg' or
                        extension == 'jpeg' or
                        extension == 'png' or
                        extension == 'gif' or
                        extension == 'ico'):
                
                    if extension == 'jpg':
                        extension = 'jpeg'
                    elif extension == 'ico':
                        extension = 'vnd.microsoft.icon'
                    
                    file_ = open(filename, 'rb')
                    log.debug('Static handler: serving %r' % filename)
                    self.response._headers = [('Content-Type', 'image/%s' %
                                                                extension)]
                    self.response._body = file_.read()
                    file_.close()
                
                else:
                    file_ = open(filename, 'r')
                    log.debug('Static handler: serving %r' % filename)
                    if extension == 'js':
                        self.response._headers = [('Content-Type',
                                                    'text/javascript')]
                    elif extension == 'css':
                        self.response._headers = [('Content-Type', 'text/css')]
                    else:
                        self.response._headers = [('Content-Type',
                                                'application/octet-stream')]

                    self.response.write(file_.read())
            except:
                # on error return a 404
                self.response.not_found()
        else:
            # it was not specified any file
            self.response.not_found()

